package com.wy.controller;

import com.wy.Service.UserService;
import com.wy.pojo.Role;
import com.wy.pojo.User;
import com.wy.vo.PageVo;
import com.wy.vo.UserDto;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Resource
    private UserService userServer;
    String msg;

    @GetMapping("/login")
    private String login(){
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, HttpSession session, Model model){
        User ac = userServer.login(username,password);
        if(ac==null){
            model.addAttribute("loginErr","密码错误");
            return "login";
        }
        session.setAttribute("loginUser",ac);
        return "redirect:/user/list";
    }

    @GetMapping("/search")
    public PageVo search(Integer current, Integer pageSize, UserDto dto){
        PageVo pageVo= userServer.searchPage(current,pageSize,dto);
        return pageVo;
    }

    @GetMapping("/list")
    public List<User> search(){
        return userServer.searchAll();
    }

    @GetMapping("/delete")
    public String delete(Integer id){
        try{
            userServer.del(id);
            msg="删除成功";
        }catch (Exception e){
            msg="删除失败";
        }
        return msg;
    }

    @GetMapping("/add")
    public String add(User user){
        try{
            userServer.add(user);
            msg="添加成功";
        }catch (Exception e){
            msg="添加失败";
        }
        return msg;
    }
}
